package utils;

import book.Book;
import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;

public class AnalyzingBorrowedBook {

    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookIds,
                            String fileName) {
        //空值判断
        if(pairOfUidAndBookIds == null) {
            return;
        }
        //计算有效记录数
        int storeUseLen = 0;
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if(pairOfUidAndBookIds[i] != null) {
                storeUseLen++;
            } else {
                break;//读取到空的数据直接退出了,因为后面用用效数遍历时也是用了 for 循环
            }
        }
        StringBuilder jsonArray = new StringBuilder();
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if(pairOfUidAndBookIds[i] != null) {
                jsonArray.append(pairOfUidAndBookIds[i].toJSON());
                if(i != storeUseLen-1) {
                    jsonArray.append("\n");
                }
            }
        }
        //数据写入文件
        FileUtils.writeFile(jsonArray.toString(),fileName);

    }

    public PairOfUidAndBookId[] loadObject(String fileName) {
        String content = FileUtils.readFile(fileName);
        //在文件为空的情况下,每生成一个普通用户对象都会报一次信息
        if(content == null || content.isEmpty()) {
            System.out.println("File is empty or does not exist: " + fileName);
            return null;
        }
        String[] storesJsonStrings = content.split("\n");

        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[storesJsonStrings.length];

        for (int i = 0; i < storesJsonStrings.length; i++) {
            pairOfUidAndBookIds[i] = parseStoreJson(storesJsonStrings[i]);
        }

        return pairOfUidAndBookIds;

    }

    private PairOfUidAndBookId parseStoreJson(String json) {
        if(json.isEmpty()) {
            return null;
        }

        String[] pairs = json.split(",");

        int userId = Integer.parseInt(pairs[0]);
        int bookId = Integer.parseInt(pairs[1]);

        PairOfUidAndBookId pairOfUidAndBookId = new PairOfUidAndBookId(userId,bookId);

        return pairOfUidAndBookId;
    }
}
